<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-02-08 20:21:43
 * @Last Modified time: 2023-02-08 20:51:09
 */
namespace app\common\services\store;

use frank\base\BaseService;
use app\common\dao\store\OrderAddressDao;
use frank\exception\CommonException;
use app\common\services\RegionService;

/**
 * 订单收货地址
 * Class OrderAddressService
 */
class OrderAddressService extends BaseService
{
    /**
     * OrderAddressService constructor.
     * @param UserAddressDao $dao
     */
    public function __construct(OrderAddressDao $dao)
    {
        $this->dao = $dao;
    }

    public function getAddressDetail($filter)
    {
        $detail = $this->dao->search($filter)->find();
        if (!$detail) {
            throw new CommonException('地址不存在');
        }
        return $detail->toArray();
    }

    public function getAddressRegionData(array $params = []){
    	$regionService = RegionService::instance();
    	$provinceId = $regionService->getIdByName($params['region'][0], 1);
        $cityId = $regionService->getIdByName($params['region'][1], 2, $provinceId);
        $regionId = $regionService->getIdByName($params['region'][2], 3, $cityId);
        // 验证城市ID是否合法
        if ($cityId <= 0) {
            _trace('system_error','选择的城市不存在');
            throw new CommonException('很抱歉，您选择的城市不存在');
        }
    	$data = [
        	'name' => $params['name'],
            'phone' => $params['phone'],
            'province_id' => $provinceId,
            'city_id' => $cityId,
            'region_id' => $regionId,
            'detail' => $params['detail'],
            'district' => ($regionId === 0 && !empty($params['region'][2])) ? $params['region'][2] : '',
        ];
    	return $data;
	}
}